package com.augurit.smartform.web.component;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.ExtBaseAction;
import com.augurit.common.base.action.ExtCrudActionSupport;
import com.augurit.common.base.extmodel.inner.MultiEntityTreeNode;
import com.augurit.common.base.form.Attachment;
import com.augurit.common.base.form.ImageForm;
import com.augurit.common.system.util.OrgUtils;
import com.augurit.common.util.ExtUtils;
import com.augurit.common.util.FileUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.smartform.constant.ComponentConstant;
import com.augurit.smartform.converter.ComponentDefinitionConverter;
import com.augurit.smartform.converter.ComponentRegisterConverter;
import com.augurit.smartform.entity.SmComponentRegister;
import com.augurit.smartform.exception.FormException;
import com.augurit.smartform.mgmt.SmartComponentTreeNode;
import com.augurit.smartform.service.IComponentDefinitionService;
import com.augurit.smartform.service.IComponentRegisterService;
import com.augurit.smartform.web.component.form.ComponentDefinitionForm;
import com.augurit.smartform.web.component.form.ComponentRegisterForm;

@Results({
	@Result(name = ExtCrudActionSupport.RELOAD, location = "component-definition.action", type = "redirect"),
	@Result(name = ExtCrudActionSupport.SUCCESS, location = "/smartform/component/definition/smart-component-definition-mgmt.jsp")
})
public class ComponentDefinitionAction extends ExtCrudActionSupport<ComponentDefinitionForm>{
	@Autowired
	private IComponentDefinitionService componentDefinitionService;
	@Autowired
	private IComponentRegisterService componentRegisterService;
	
	public static final String IMG_PATH = "/smartform/component/definition/img/icon";
	public static final String SMALL_IMG = "16_16";
	
	private String nodeId;	//页面管理树结点ID，由 Entity类名 + "#" + Entity对象ID 组成 
	private ComponentDefinitionForm form;
	private Page<ComponentDefinitionForm> page=new Page<ComponentDefinitionForm>(10);
	private Long id;		
	private Long[] ids;
	private String filetype;//1:XML文件,2:图标,3:视图图片
	
	/**
	 * 获取小图标文件列表信息
	 */
	public String getSmallImages() throws Exception {
		List<ImageForm> fileList = loadImages();
		this.extRenderListJson(fileList, true);
		return null;
	}
	
	/**
	 * 修改组件图标
	 */
	public void updateIcon(){
		try {
			componentDefinitionService.updateIcon(form);
			this.extRenderSuccess();
		} catch (FormException e) {
			this.extRenderFailture(e.getMessage());
		}
	}
	
	/**
	 * 上传组件定义文件
	 */
	public void uploadComponent(){
		if("1".equals(filetype)){
			uploadXmlFile();
		}else if("2".equals(filetype)){
		}else if("3".equals(filetype)){
		}
	}
	
	/**
	 * 下载组件定义文件
	 * @throws IOException 
	 */
	public void downloadComponent() throws IOException{
		InputStream in = null;
    	ServletOutputStream out = null;
         	
         //重置response
    	BaseAction.getResponse().reset();
    	BaseAction.getResponse().setContentType("application/octet-stream");
    	String fileName = form.getTag()+ComponentConstant.XML_SUFFIX;
    	BaseAction.getResponse().setHeader("Content-Disposition","attachment; filename=" + fileName);
    	in = new BufferedInputStream(new ByteArrayInputStream(form.getContent().getBytes("UTF-8")));
    	out = BaseAction.getResponse().getOutputStream();
        FileUtils.copy(in, out);
	}
	
	/**
	 * 禁用组件
	 */
	public void disable(){
		if(ids!=null){
			try {
				for(Long id : ids){
					ComponentDefinitionForm disableForm=componentDefinitionService.get(id);
					componentDefinitionService.disable(disableForm);
				}
				this.extRenderSuccess();
			} catch (FormException e) {	
				this.extRenderFailture(e.getMessage());
			}
		}
	}
	
	/**
	 * 启用组件
	 */
	public void enable(){
		if(ids!=null){
			try {
				for(Long id : ids){
					ComponentDefinitionForm enableForm=componentDefinitionService.get(id);
					componentDefinitionService.enable(enableForm);
				}
				this.extRenderSuccess();
			} catch (FormException e) {	
				this.extRenderFailture(e.getMessage());
			}
		}
	}
	
	/**
	 * 拖拽组件
	 */
	public void dragComponent(){
		try {
			componentDefinitionService.dragComponent(form);
			this.extRenderSuccess();
		} catch (FormException e) {
			this.extRenderFailture(e.getMessage());
		}
	}
	
	/**
	 * 组件管理的树列表
	 */
	public void getComponentTree(){
		MultiEntityTreeNode node = SmartComponentTreeNode.build(nodeId);
		List<SmartComponentTreeNode> result=this.getChildren(node);
		this.extRenderListJson(result, false);
	}
	
	@Override
	public String delete(){
		if(ids!=null){
			try {
				for(Long id : ids){
					ComponentDefinitionForm enableForm=componentDefinitionService.get(id);
					componentDefinitionService.delete(enableForm);
				}
				this.extRenderSuccess();
			} catch (Exception e) {	
				this.extRenderFailture(e.getMessage());
			}
		}
		return null;
	}

	@Override
	public String list() throws Exception {
		ExtUtils.initPageFromExtGridParam(getRequest(), page);
		componentDefinitionService.search(page, form);
		ExtBaseAction.extRenderGridJson(page);
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		if(id!=null){
			form=componentDefinitionService.get(id);
		}else{
			form=new ComponentDefinitionForm();
		}
	}
	
	/**
	 * 加载组件视图数据
	 */
	@Override
	public String input() throws Exception {
		this.extRenderFormJson(form);
		return null;
	}
	
	@Override
	public String save() throws Exception {
		componentDefinitionService.save(form);
		this.extRenderFormJson(form);
		return null;
	}

	public ComponentDefinitionForm getModel() {
		// TODO Auto-generated method stub
		return form;
	}

	/**
	 * 上传组件定义XML文件
	 */
	private void uploadXmlFile(){
		try{
			if(form.getId()!=null){
				form.setEditPerson(this.getLoginUserName());
			}else{
				form.setCreatePerson(this.getLoginUserName());
			}
    		List<Attachment> attachments = this.getAttachmentList();
        	if(attachments != null && attachments.size() > 0){
        		for(Attachment attachment:attachments){
        			componentDefinitionService.handleXmlFile(attachment,form);
        		}
        	}
        	this.renderText("successed");
    	}catch(FormException e){
    		this.renderText(e.getMessage());
    	}
	}
	
	/**
	 * 获取树节点下面子节点的数据
	 * @param node
	 * @return
	 */
	private List<SmartComponentTreeNode> getChildren(MultiEntityTreeNode node){
		List<SmartComponentTreeNode> result=new ArrayList<SmartComponentTreeNode>();
		if(node != null){
			if(MultiEntityTreeNode.isRootNode(node.getId())){
				List<ComponentRegisterForm> list=componentRegisterService.getAllComponentRegister();
				result=ComponentRegisterConverter.convertComponentRegisterToTreeNode(list);
			}else if(node.getEntityName().equals(SmComponentRegister.class.getSimpleName())){
				Long registerId=node.getEntityId();
				List<ComponentDefinitionForm> list=componentDefinitionService.getDefinitionByRegisterId(registerId);
				result=ComponentDefinitionConverter.convertComponentDefintionToTreeNode(list);
			}
		}
		return result;
	}

	/**
	 * 加载图标物理文件数据
	 * @return
	 */
	private List<ImageForm> loadImages(){
		
		//项目在服务器上的绝对文件路径
		String realPath = this.getApplication().getRealPath("/");               

		//图标在服务器上的绝对文件路径
		String imgFolderPath = realPath + IMG_PATH;
		
		//图标相对于项目的访问路径
		String appName = this.getRequest().getContextPath();
		String imgFolderInApp = appName  + IMG_PATH + "/";	//如：/framework/resources/images/icons/16_16
        
		//先检查缓存中是否存在
		List<ImageForm> list = null;
		
		if(list == null || list.size() == 0){		
			File imgFolder = new File(imgFolderPath);
			if(imgFolder.exists() && imgFolder.isDirectory()){
				
				//图标文件列表
				File[] files = imgFolder.listFiles();
				if(files != null && files.length > 0){
					list = new ArrayList();
					for(File file : files){
						ImageForm form = new ImageForm();
						form.setName(file.getName());
						form.setShortName("");
						form.setUrl(imgFolderInApp + form.getName());
						form.setSize(SMALL_IMG);
						list.add(form);
					}
				}
			}
		}
		
		return list;
	}
	
	/***************************************************
	 * get和set方法
	 ***************************************************/
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getIds() {
		return ids;
	}

	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public Page<ComponentDefinitionForm> getPage() {
		return page;
	}

	public void setPage(Page<ComponentDefinitionForm> page) {
		this.page = page;
	}

	public String getFiletype() {
		return filetype;
	}

	public void setFiletype(String filetype) {
		this.filetype = filetype;
	}

	public String getNodeId() {
		return nodeId;
	}

	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}
}
